package com.experient.test;

import android.accounts.NetworkErrorException;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.experient.test.api.GetTableList;
import com.experient.test.struct.Table;
import com.nostra13.dcloudimageloader.utils.L;
import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static android.content.Context.MODE_PRIVATE;

/**
 * @author 刘威
 */
public class SingleTimetable extends AppWidgetProvider {


    /**
     * 课表更新事件
     */
    private static final String UPDATE_ACTION2 = "TABLE_UPDATE_ACTION2";
    private static final String UPDATE_ACTION = "TABLE_UPDATE_ACTION";

    /**
     * 更新时获取数据用的安全吗
     */
    private String SafeCode;

    @SuppressLint("Range")
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);

        //获取存在数据库中的安全码
        SQLiteDatabase db = context.openOrCreateDatabase("DCStorage", MODE_PRIVATE, null);;
        Cursor cursor = db.query("DC_1908175602_storage", null, "key=?", new String[]{"SafeCode"}, null, null, null);
        if (cursor.moveToFirst()) {
            SafeCode = cursor.getString(cursor.getColumnIndex("value"));
            cursor.close();
        }

        db.close();


        //创建线程池来获取课程表数据
        ThreadFactory threadFactory = Thread::new;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), threadFactory);
        threadPoolExecutor.execute(() -> {
            try {

                //获取课表数据
                Map tableList = GetTableList.getTableData(SafeCode);

                List<Map> tableList1 = (List<Map>) tableList.get("classTable");

                List<Table> tableList2 = new ArrayList<>();

                for (Map map : tableList1) {
                    Table table = new Table();
                    table.setClassName((String) map.get("subject"));
                    table.setRoomName((String) map.get("classroom"));
                    table.setTeacherName((String) map.get("teacher"));
                    table.setSection((String) map.get("section"));
                    table.setFromTime((String) map.get("fromTime"));
                    table.setToTime((String) map.get("toTime"));

                    tableList2.add(table);
                }

                //对tableList2进行排序
                Collections.sort(tableList2);

                String week = (String) tableList.get("week");
                String day = (String) tableList.get("day");

                Log.d("小部件二","更新列表"+week+" "+day);

                //更新界面,设置一下时间
                RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget_2);
                remoteViews.setTextViewText(R.id.weekData2, "第"+week+"周 / "+day);

                TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));

                //获取当前时间离今天零点的秒数
                @SuppressLint("SimpleDateFormat") int hour = Integer.parseInt(new SimpleDateFormat("HH").format(new Date()));
                @SuppressLint("SimpleDateFormat") int minute = Integer.parseInt(new SimpleDateFormat("mm").format(new Date()));
                @SuppressLint("SimpleDateFormat") int second = Integer.parseInt(new SimpleDateFormat("ss").format(new Date()));

                int nowTime = hour*3600+minute*60+second;

                long toTime;

                Table next = null;



                int except = tableList2.size();
                for (Table t : tableList2) {

                    except--;

                    toTime = t.getToTimeInt();

                    //如果当前时间小于结束时间，则结束循环
                    if (nowTime < toTime) {
                        next = t;
                        break;
                    }
                }

                if(next != null) {

                    String detail = next.getSection() + "节|" +next.getRoomName() + "|" + next.getTeacherName();


                    remoteViews.setViewVisibility(R.id.noClass, View.GONE);
                    remoteViews.setViewVisibility(R.id.hasClass, View.VISIBLE);


                    remoteViews.setTextViewText(R.id.className2, next.getClassName());

                    remoteViews.setTextViewText(R.id.classDetail2, detail);

                    remoteViews.setTextViewText(R.id.fromTimeText2, next.getFromTime());
                    remoteViews.setTextViewText(R.id.toTimeText2, next.getToTime());
                }else{
                    remoteViews.setViewVisibility(R.id.noClass, View.VISIBLE);
                    remoteViews.setViewVisibility(R.id.hasClass, View.GONE);
                }

                remoteViews.setTextViewText(R.id.courseNum,"还有其他"+except+"节课程哟~~");



                //通知刷新页面
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
                ComponentName componentName = new ComponentName(context, SingleTimetable.class);
                appWidgetManager.updateAppWidget(componentName, remoteViews);

            } catch (NetworkErrorException | JSONException e) {
                e.printStackTrace();
            }
        });

    }

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget_2);

        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget_2);

            //设置刷新按钮点击事件
            Intent clickIntent = new Intent().setAction(UPDATE_ACTION2);

            clickIntent.setPackage(context.getPackageName());
            clickIntent.setComponent(new ComponentName(context, SingleTimetable.class));

            @SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.refresh2, pendingIntent);


            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
    }

    @Override
    public void onEnabled(Context context) {


//        IntentFilter filter = new IntentFilter();
//        filter.addAction(UPDATE_ACTION2);
//        filter.addAction(UPDATE_ACTION);
//        context.getApplicationContext().registerReceiver(this,filter);


        super.onEnabled(context);

    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}